<!--图片，附件调用接口上传组件-->
<template>
  <div class="component-upload-image">
    <el-upload
      action=""
      :http-request="httpRequest"
      :list-type="listType"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleError"
      :on-exceed="handleExceed"
      name="file"
      :on-remove="handleRemove"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{ 'is-hide': fileList.length >= limit }"
    >
      <i v-if="listType=='picture-card'" class="el-icon-plus" />
      <el-button v-else size="mini" type="primary">选取文件</el-button>
    </el-upload>

    <!-- 上传提示 -->
    <div v-if="showTip" slot="tip" class="el-upload__tip">
      请上传
      <template v-if="fileWidth"> 宽高 <b style="color: #f56c6c">({{ fileWidth }}*{{ fileHeight }})</b> </template>
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType&&fileType.length>0"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>

    <!--预览组件-->
    <PreView :is-menu-show='false'
             :v-model:visible="dialogVisible"
             v-if="dialogVisible"
             :fileArr="previewData"
             @close="dialogVisible=false"
    ></PreView>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import PreView from '@/components/Preview-Files/index.vue';
import {postUpload} from '@/api/system/upload'
export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    dir: {
      type: String,
      default: 'image'
    },
    // 宽
    fileWidth: {
      type: Number
    },
    // 高
    fileHeight: {
      type: Number
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg','.mp4', '.webm' , '.mov','.mp3', '.wma' , '.wav']等
    fileType: {
      type: Array,
      default: () => []//
    },
    listType: {//上传类型 	text/picture/picture-card 其中text附件上传
      type: String,
      default: 'picture-card'
    }
  },
  components: {
    PreView,
  },
  data() {
    return {
      previewData:[],
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: [],
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === 'string') {
              item = { name: item, url: item };
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  methods: {
    handleError(error, file, fileList) {
      // 处理上传失败的情况
      console.error('上传失败', error);
      console.error('上传失败file', file);
      console.error('上传失败fileList', fileList);
      // 可以选择将失败的文件从 fileList 中移除
      // const index = fileList.indexOf(file);
      // if (index !== -1) {
      //   fileList.splice(index, 1);
      // }
    },
    // 删除图片
    handleRemove(file, fileList) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      this.fileList.splice(findex, 1);
      this.$emit('input', this.listToString(this.fileList));
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = '';
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf('image') > -1;
      }

      if (!isImg) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }

      // 计算图片的宽高比例
      if (this.fileWidth) {
        const url = window.URL || window.webkitURL;
        const image = new Image();
        image.src = url.createObjectURL(file);
        const that = this;
        image.onload = function() {
          if (image.width / image.height !== that.fileWidth / that.fileHeight) {
            that.$message.error(`图片宽高比例不合适, 请上传宽高为${that.fileWidth}*${that.fileHeight}的图片!`);
            return false;
          }
        };
      }
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.name;
      this.previewData = [];
      this.previewData.push({
        url: file.url || file.response.data.link,
        name: file.name||Date.now().toString(),
      });
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = '';
      separator = separator || ',';
      for (const i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    //注：此处改成项目中的实际上传路径
    httpRequest(e) {
      postUpload(e.file).then(res => {
        if (res.code == 200) {
          this.fileList.push({
            ...res.data,
            name: e.file.name, url: res.data.fullUrl, });
          this.$emit('input', this.listToString(this.fileList), this.fileList);
          this.loading.close();
          return e.file;
        }
      }).catch(error => {
        console.log("上传错误",error)
        this.loading.close();
      })

    },
  }
};
</script>
<style scoped lang="scss">
//控制新增图片上传按钮
.is-hide ::v-deep .el-upload--picture-card {
  display: none !important;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
    transition: all 0s;
}

::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
}
</style>

